import 'package:ai/page/chat/MessageItem.dart';
import 'package:auto_route/annotations.dart';
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

import '../../config/Config.dart';
import '../../entity/TextMessage.dart';
import '../../util/CommonUtils.dart';
import '../../util/event_stream_util.dart';

@RoutePage()
class ChatMessagePage extends StatefulWidget {
  const ChatMessagePage({super.key});

  @override
  State<ChatMessagePage> createState() => _ChatMessagePageState();
}

class _ChatMessagePageState extends State<ChatMessagePage> {
  late List<TextMessage> _list = [];

  late String _question = "";

  late bool _isEnd = true;

  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();

  final TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();

  }

  void _send() {
    var content = _question;
    _textEditingController.clear();
    List<TextMessage> newList = [];
    newList.addAll(_list);
    newList.add(TextMessage.create(_question, 1));
    setState(() {
      _question = "";
      _list = newList;
    });
    itemScrollController.scrollTo(
      index: _list.length+1,
      duration: const Duration(milliseconds: 500),
    );

    EventStreamManager.send("${Config.baseUrl}/member/message", {
      'content': content,
    }, (TextMessage message) {
      if (message.finishReason == "stop") {
        setState(() {
          _isEnd = true;
        });
        itemScrollController.scrollTo(
          index: _list.length+1,
          duration: const Duration(milliseconds: 500),
        );
      } else {
        setState(() {
          _isEnd = false;
        });
      }
      getAnswer(message);
      itemScrollController.scrollTo(
        index: _list.length+1,
        duration: const Duration(milliseconds: 500),
      );
    }, () {
      setState(() {
        _isEnd = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: const Text("甄嬛"),
        leading: BackButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        actions: [
          GestureDetector(
            onTap: (){
              _list = [];
              setState(() {

              });
            },
            child: Row(
              children: [
                CommonUtils.getImageAsset("loading", width: 18),
                const Text("重置"),
                const SizedBox(
                  width: 8,
                ),
              ],
            ),
          )
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: ScrollablePositionedList.builder(
          itemCount: _list.length+1,
          itemScrollController: itemScrollController,
          itemPositionsListener: itemPositionsListener,
          itemBuilder: (BuildContext context, int index) {
            if(index==_list.length){
              return Container(
                height: 1,
              );
            }
            return MessageItem(content: _list[index].content, type: _list[index].type);
          },
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color: Config.color6f,
        child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            Expanded(
              child: getInput(),
            ),
            IconButton(
              onPressed: () {
                if (_isEnd) {
                  _send();
                }
              },
              icon: Icon(
                _isEnd?Icons.send_rounded:Icons.map,
                color: Config.primaryColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget getInput() {
    return TextField(
      controller: _textEditingController,
      onChanged: (value) {
        setState(() {
          _question = value;
        });
      },
      decoration: InputDecoration(
        fillColor: Colors.white,
        filled: true,
        hintText: "想和我聊点什么?",
        enabledBorder: OutlineInputBorder(
          borderSide: const BorderSide(
            color: Colors.white,
            width: 1,
          ),
          borderRadius: BorderRadius.circular(32),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: const BorderSide(
            color: Colors.white,
            width: 1,
          ),
          borderRadius: BorderRadius.circular(32),
        ),
      ),
    );
  }

  void getAnswer(TextMessage message) {
    var value =
        _list.isNotEmpty ? _list[_list.length - 1] : TextMessage.copy(message);
    if (value.requestId == message.requestId) {
      value.content = value.content + message.content;
      value.outputTokens = message.outputTokens;
      value.inputTokens = message.inputTokens;
      value.totalTokens = message.totalTokens;
    } else {
      var copy = TextMessage.copy(message);
      List<TextMessage> newList = [];
      newList.addAll(_list);
      newList.add(copy);
      setState(() {
        _list = newList;
      });
    }
    setState(() {});
  }
}
